import React, { useEffect, useState } from "react";
import { Form, InputNumber, message, notification, Select, Checkbox, Input, Button, Upload } from "antd";
import { CommonModal } from "@/views/components/CommonModal";
import CommonLoading from "@/components/CommonLoading";
import { manualDelivery, batchPrintByQualifiedOutbound, getCoFcTemplateByIdsOutbound } from "../service";
import { printCard } from "@/utils/print.jsx";
// import {
// 	checkComponentsIsOpen,
// 	getAllPrinter,
// 	judgeHasWhichPlatform,
// 	print,
// 	printCheckList,
// 	printVipShop
// } from "@/utils/print.jsx";
import styles from "./index.module.less";
import { logisticsCompanyList } from "@/utils/config";

import { setPrinterName, getPrinterName, getCurrentUser } from "@/utils/authority";
import { hiprint } from "vue-plugin-hiprint";
import { getAllPrinter } from "@/utils/print.jsx";
import { isEmpty } from "lodash";

const Modal = ({ visible, title, modelType, ids, checkedRows, onOk, onCancel, width = "520px" }) => {
	const [loading, setLoading] = useState(false);
	//打印机列表
	const [printData, setPrintData] = useState([]);
	const [template, setTemplate] = useState([]);
	useEffect(() => {
		if (visible) {
			["certificatePrint", "batchPrint"].includes(modelType) && getAllPrinter(value => setPrintData(value));
			form.resetFields();
		}
	}, [visible]);

	const [form] = Form.useForm();

	//打印队列渲染输出
	const realPrint = (runner, done, printData, printer) => {
		hiprintTemplate = new hiprint.PrintTemplate({ template });

		console.log("template", template);

		hiprintTemplate.on("printSuccess", function () {
			printData.uniqueCode && printedArr.push(printData.uniqueCode);
			console.log("printedArr", printedArr);
			if (!runner?.tasks?.list?.length || printedArr?.length == 10) {
				callBack();
			}
			done();
		});
		hiprintTemplate.on("printError", function () {
			if (!runner?.tasks?.list?.length) {
				callBack();
			}
			done();
		});
		hiprintTemplate.print2(printData, { printer });
	};

	/** 合格证打印相关start */

	const printQueenArr = [];
	let isPrinting = false; // 是否正在打印， 正在打印的数组

	let hiprintTemplate,
		printedArr = [],
		runner;

	// 设置打印机名称
	const handlePrinterName = name => {
		setPrinterName(name);
	};

	/** 合格证打印相关end */

	const handleOk = () => {
		form
			.validateFields()
			.then(async val => {
				// message.success("操作完成！");
				console.log(checkedRows);
				// 合格证打印
				if (modelType === "certificatePrint") {
					const task = [];
					printData.map(item => {
						task.push(done => {
							realPrint(runner, done, item, printer);
						});
					});
					runner.addMultiple(task);
					message.success(`即将打印${printData.length}个合格证，请等待`);
					onCancel();
					// const ids = checkedRows.map(e => e.outboundNo);
					// // 获取打印数据
					// const res = await batchPrintByQualifiedOutbound(ids);
					// if (res.code === 200) {
					// 	console.log(res);
					// } else {
					// 	message.error(res.msg);
					// }
					// // 获取打印模板
					// const templateData = await getCoFcTemplateByIdsOutbound([1]);
					// console.log("templateData", templateData);
					// // printCard({ type: 1, data: { ...templateData, templateValue: JSON.stringify(templateData.templateValue) } });
					// let index = 0;
					// ids.forEach(outboundNo => {
					// 	Object.keys(res.data[outboundNo]).forEach(goodId => {
					// 		console.log("开始打印", index);
					// 		index++;
					// 		printCard({ type: 1, data: { ...templateData }, goods: res.data[outboundNo][goodId], index });
					// 	});
					// });
				}

				onOk();
			})
			.catch(err => {
				console.log(err, "err");
			});
	};

	// 打印机选择框
	const renderPrintFn = () => (
		<Select placeholder="请选择打印机" onChange={handlePrinterName}>
			{!isEmpty(printData) &&
				printData.map(d => (
					<Option key={d} value={d}>
						{d}
					</Option>
				))}
		</Select>
	);

	// 手动发货
	const manualShipmentDomFn = () => {
		return (
			<>
				<div>共包含订单数：{ids.length}</div>
				<Form.Item
					label="请输入包裹重量"
					name="weight"
					rules={[
						{
							required: true,
							message: "请输入包裹重量"
						},
						{
							pattern: /^(0|[1-9][0-9]*){1}(\.[0-9]{1,2})?$/,
							message: "包裹重量必须是数字，大于等于0且只能最多有二位小数"
						}
					]}
				>
					<InputNumber min={0} step={0.01} style={{ width: 100 }} placeholder="kg" />
				</Form.Item>
				<div>
					<p className="common-color9">注：</p>
					<p className="common-color9">普通订单和一单多包的订单，建议分开勾选操作</p>
					<p className="common-color9">如果勾选订单里有这两种订单，会跳过“一单多包”订单</p>
				</div>
			</>
		);
	};
	// 合格证打印
	const certificatePrintDomFn = () => {
		return (
			<>
				<Form.Item label="订单数量" name="orderCount">
					<div>{ids.length}</div>
				</Form.Item>
				<Form.Item label="打印机" name="printer" rules={[{ required: true, message: "请选择打印机" }]}>
					{renderPrintFn()}
				</Form.Item>
			</>
		);
	};

	// 快递操作
	const operateDeliveryDomFn = () => {
		return (
			<>
				{modelType === "batchPrint" && (
					<>
						<Form.Item label="订单数量" name="orderCount">
							<div>{ids.length}</div>
						</Form.Item>
						<Form.Item label="快递公司1" name="printer" rules={[{ required: true, message: "请选择打印机" }]}>
							{renderPrintFn()}
						</Form.Item>
						<Form.Item label="快递公司2" name="printer" rules={[{ required: true, message: "请选择打印机" }]}>
							{renderPrintFn()}
						</Form.Item>
					</>
				)}
				{["updateDelivery", "batchUpdateDelivery"].includes(modelType) && (
					<>
						<Form.Item label="快递公司名称" name="logisticsCompany" rules={[{ required: true, message: "请选择快递公司" }]}>
							<Select placeholder="请选择快递公司">
								{logisticsCompanyList.map((item, index) => (
									<Option key={index} value={item}>
										{item}
									</Option>
								))}
							</Select>
						</Form.Item>
						{modelType === "updateDelivery" && (
							<>
								<Form.Item label="快递运单号" name="logisticsNo" rules={[{ required: true, message: "请输入快递运单号" }]}>
									<Input placeholder="请输入快递运单号" autoComplete="off" />
									<p className="common-color5" style={{ fontSize: "12px", padding: "12px 8px 0" }}>
										注：手动更改过的物流信息不支持打印快递面单
									</p>
								</Form.Item>
							</>
						)}
						{modelType === "batchUpdateDelivery" && (
							<>
								<Form.Item
									label="快递运单号"
									valuePropName="checked"
									name="logisticsNo"
									rules={[{ required: true, message: "请输入快递运单号" }]}
								>
									<Checkbox>自动获取运单号</Checkbox>
								</Form.Item>
							</>
						)}
					</>
				)}
				{modelType === "batchExport" && (
					<>
						<div className="flex" style={{ justifyContent: "space-around" }}>
							<Button shape="round" size="default" onClick={handleExport}>
								导出表格
							</Button>
							<Upload {...props}>
								<Button shape="round" size="default" icon={null}>
									导入表格
								</Button>
							</Upload>
						</div>
						<div style={{ marginTop: "30px" }}>
							<p className="common-color9">注：</p>
							<p className="common-color9">
								批量修改需先将需要修改的订单进行导出，在表格内修改完成后再次进行导入系统即可完成修改
							</p>
						</div>
					</>
				)}
			</>
		);
	};

	// 获取运单号
	const getTrackNumDomFn = () => {
		return (
			<>
				<Form.Item label="共包含订单数">
					<div>{ids.length}</div>
				</Form.Item>
				<Form.Item label="确定批量获取运单号吗？" colon={false}></Form.Item>
			</>
		);
	};

	const props = {
		// name: "file",
		// // action: `${httpChange(UPLOAD_SERVER)}/zjf-wms/wmsorder/manual/importPage`,
		// headers: {
		// 	"Blade-Auth": getToken()
		// },
		// accept: ".xlsx",
		// showUploadList: false,
		// beforeUpload(file) {},
		// onChange(info) {}
	};

	const handleExport = () => {
		// if (total) {
		// 	const nums = Math.ceil(total / 10000);
		// 	message.info(`即将为您导出${nums}张Excel, 请稍候`);
		// 	let current = 0;
		// 	const loopExportFunc = () => {
		// 		current++;
		// 		requestParams.current = current;
		// 		requestParams.size = 10000;
		// 		handleExportExcel(`/zjf-wms/wmsorder/manual/exportPage?${stringify(requestParams)}`, "手动修改物流信息.xlsx", () => {
		// 			if (current < nums) {
		// 				loopExportFunc();
		// 			}
		// 			setLoading(false);
		// 			handleCancel();
		// 		});
		// 	};
		// 	setLoading(true);
		// 	loopExportFunc();
		// } else {
		// 	message.info("暂无可导出的数据！");
		// }
	};

	return (
		<CommonModal title={{ title }} visible={visible} onCancel={onCancel} onOk={handleOk} width={width}>
			<Form name="send-goods-modal" form={form}>
				{modelType === "manualShipment" && manualShipmentDomFn()}
				{modelType === "certificatePrint" && certificatePrintDomFn()}
				{modelType === "getTrackNum" && getTrackNumDomFn()}
				{operateDeliveryDomFn()}
			</Form>
			<CommonLoading loading={loading} />
		</CommonModal>
	);
};

export default Modal;
